package com.retlife.tvshow.serial_port

import android.serialport.SerialPortFinder
import java.io.File

/**
 * 串口管理类
 */
class BaseSerialManage(
    private val devicePath: String,
    private val baudrate: Int,
    private val isRead: Boolean,
    flags: Int,
    dataBits: Int,
    stopBits: Int,
    parity: Int,
    baseSerialReceiver: BaseSerialReceiver?
) {
    private var baseSerialPoster: BaseSerialPoster? = null //串口连接 发送 读取处理对象

    init {
        if (baseSerialPoster == null) {
            baseSerialPoster = BaseSerialPoster(dataBits, stopBits, parity, flags)
        }
        baseSerialPoster?.addSerialInter(baseSerialReceiver)
    }

    fun startTest() {
        baseSerialPoster!!.startTest()
    }

    /**
     * 打开串口
     * @return
     */
    fun open(): Boolean {
//        isConnect = baseSerialHandle.open("/dev/ttyS1", 9600, true);//设置地址，波特率，开启读取串口数据
        //串口是否连接
        val isConnect: Boolean = baseSerialPoster!!.open(devicePath, baudrate, isRead)
        if (isConnect) {
            baseSerialPoster!!.startSendTask()
        }
        return isConnect
    }

    /**
     * 发送指令
     *
     * @param msg
     */
    fun send(msg: ByteArray) {
        baseSerialPoster!!.send(msg)
    }

    /**
     * 关闭串口
     */
    fun colse() {
        baseSerialPoster!!.close() //关闭串口
    }

    companion object {
        val serialFiles: List<String>
            get() {
                val files: MutableList<String> = ArrayList()
                val finder:SerialPortFinder = SerialPortFinder()
                val allDevices = finder.allDevices
                allDevices?.let {
                    for (file: String in it) {
                        if (file.startsWith("tty")) {
                            files.add(file)
                        }
                    }
                }

                return files
            }
    }
}
